package com.hdl.provider;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 类名 ServiceRegistry
 * 描述 服务注册
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/6/17 16:06
 */
@Component
public class ServiceRegistry {
    /**
     * 服务提供者节点
     */
    private static String SERVICE_PROVIDER = "/service_provider";

    @Autowired(required = false)
    private CuratorFramework zkClient;

    /**
     * 服务注册
     * @param data 注册的数据
     */
    public void register(String data){
        if (zkClient != null){
            createNode(SERVICE_PROVIDER, data);
        }
    }

    /**
     * 创建节点
     * @param serverPath 节点路径
     * @param data 数据
     */
    private void createNode(String serverPath, String data){
        try {
            Stat stat = zkClient.checkExists().forPath(serverPath + "/" + data);
            if (stat == null){
                zkClient.create()
                        // 递归创建
                        .creatingParentsIfNeeded()
                        // 创建临时节点
                        .withMode(CreateMode.EPHEMERAL)
                        // 创建路径
                        .forPath(serverPath + "/" + data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("创建节点失败");
        }
    }
}
